import requests
from lxml import etree
import csv
import os


def init():
    if not os.path.exists('./cityData.csv'):
        with open('./cityData.csv', 'w', encoding='utf-8', newline='') as fw:
            writer = csv.writer(fw)
            writer.writerow(['city', 'cityLink'])


def writerRow(row):
    with open('./cityData.csv', 'a', encoding='utf-8', newline='') as fw:
        writer = csv.writer(fw)
        writer.writerow(row)


def getHtml(url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36'
    }
    resp = requests.get(url, headers=headers)
    if resp.status_code == 200:
        return resp.text
    return None


def parseHtml(html):
    root = etree.HTML(html)
    cityList = root.xpath('//div[@class="fc-main clear"]//li//a')
    for city in cityList:
        cityName = city.text
        cityLink = city.get('href') + '/loupan/pg1/?_t=1'
        # print(f'-- city: {cityName} --> {cityLink}')
        writerRow([cityName, cityLink])
    return


def main():
    init()

    html = getHtml('https://gz.fang.lianjia.com/loupan/')
    if html:
        parseHtml(html)


if __name__ == '__main__':
    main()